package com.zh.springcloud.config;

import com.alibaba.druid.pool.DruidDataSource;
import io.seata.rm.datasource.DataSourceProxy;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.transaction.SpringManagedTransactionFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;



/**
 * 数据源代理
 */
@Configuration
public class DataSourceConfiguration {

//	@Value("${spring.datasource.url}")
//	private String url;
//	@Value("${spring.datasource.username}")
//	private String username;
//	@Value("${spring.datasource.password}")
//	private String password;
//	@Value("${spring.datasource.driver-class-name}")
//	private String driverClassName;


	@Bean
	@ConfigurationProperties(prefix = "spring.datasource")
	public DataSource druidDataSource(){
		DruidDataSource druidDataSource = new DruidDataSource();
//		druidDataSource.setUrl(url);
//		druidDataSource.setUsername(username);
//		druidDataSource.setPassword(password);
//		druidDataSource.setDriverClassName(driverClassName);
		return druidDataSource;
	}

	@Primary
	@Bean("dataSource") //6.1 创建DataSourceProxy
	public DataSourceProxy dataSourceProxy(DataSource druidDataSource){
		return new DataSourceProxy(druidDataSource);
	}

//	@Bean //6.2 将原有的DataSource对象替换为DataSourceProxy
//	public SqlSessionFactory sqlSessionFactory(DataSourceProxy dataSourceProxy)throws Exception{
//		SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
//		sqlSessionFactoryBean.setDataSource(dataSourceProxy);
//		sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver()
//				.getResources("classpath*:mapper/*Mapper.xml"));
//		sqlSessionFactoryBean.setTransactionFactory(new SpringManagedTransactionFactory());
//		return sqlSessionFactoryBean.getObject();
//	}

}
